<template>
  <div class="authority">
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
      </div>
      <el-table :data="gzlData" row-key="id">
        <el-table-column align="left" label="名称" prop="name"></el-table-column>
        <el-table-column align="left" label="类型" prop="name">
          <template #default="scope">
                <span>{{ typeList[scope.row.type-1].name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editData(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div> -->
    </div>
    <el-drawer v-model="dialog1" :size="1000" :before-close="handleClose1" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">维修管理</span>
          <div>
            <el-button @click="closeDialog1">取消</el-button>
            <el-button @click="confirm1" type="primary">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialog1" ref="gzlForm" label-width="150" :model="forms" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="forms.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="forms.type" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-card style="margin: 40px auto 0 110px;width:850px;">
          <template #header>
            <div class="card-header">
              <span>工作流配置</span>
            </div>
          </template>
          <el-steps direction="vertical" :active="active" finish-status="success">
            <el-step v-for="(item, index) in forms.nodes">
              <template #icon>
                <el-icon v-if="index + 1 == forms.nodes.length" :size="30" color="#3b82f6" style="cursor: pointer;"
                  @click="addProcess(index)">
                  <CirclePlus />
                </el-icon>
                <el-icon v-else :size="30" color="#67c23a" style="cursor: pointer;">
                  <CircleCheck />
                </el-icon>
              </template>
              <template #title>
                <div style="font-size: 20px;cursor: pointer;display: flex;margin-bottom: 10px;">
                  <span v-if="forms.nodes.length == 1" style="width: 300px;display: inline-block;">{{
                    forms.nodes[currentIndex].node
                  }}</span>
                  <span v-else style="width: 300px;display: inline-block;font-weight: normal;"
                    :class="index + 1 == forms.nodes.length ? '' : 'green'">{{ forms.nodes[index].node }}</span>
                  <el-button type="primary" style="margin-top: -4px;" @click="openDialog(index)">选择</el-button>
                  <el-button v-if="index > 0" type="danger" style="margin-top: -4px;"
                    @click="delProcess(index)">删除</el-button>
                </div>
              </template>
              <template #description>
                <div style="margin-bottom: 20px;">
                  <div v-for="item2 in item.names" style="margin-bottom: 4px;color: #000;">
                    {{ item2 }}</div>
                </div>
              </template>
            </el-step>
          </el-steps>
        </el-card>
      </el-form>

    </el-drawer>

    <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">选择</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button @click="confirm" type="primary">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="forms">
        <el-form-item label="节点名" prop="node">
          <el-input v-model="forms.nodes[currentIndex].node" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input v-model.number="forms.nodes[currentIndex].sort" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="forms.nodes[currentIndex].type" class="ml-4">
            <el-radio :value="1" size="large">选择角色</el-radio>
            <el-radio :value="2" size="large">选择用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择用户" v-if="forms.nodes[currentIndex].type == 2">
          <el-input v-model="forms.nodes[currentIndex].names" placeholder="请选择" @click.native="openUser"></el-input>
        </el-form-item>
        <el-form-item label="角色" v-else>
          <el-select v-model="forms.nodes[currentIndex].elements" multiple placeholder="请选择" style="width: 100%">
            <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批条件" prop="type">
          <el-radio-group v-model.number="forms.nodes[currentIndex].condition" class="ml-4">
            <el-radio :value="1" size="large">会签</el-radio>
            <el-radio :value="2" size="large">或签</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer v-model="dialog2" :size="1000" :before-close="handleClose2" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">选择</span>
          <div>
            <el-button @click="closeDialog2">取消</el-button>
            <el-button @click="confirm2" type="primary">确定</el-button>
          </div>
        </div>
      </template>
      <div class="top">
        <div class="search">
          <el-form :inline="true">
            <el-form-item label="姓名">
              <el-input v-model="form.name" style="width:170px" placeholder="请输入" />
            </el-form-item>
            <el-form-item style="margin-right: 0;">
              <el-button type="primary" icon="search" @click="search">
                查询
              </el-button>
              <el-button icon="refresh" @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <el-table ref="table" :data="userData" row-key="id" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="头像">
          <template #default="scope">
            <img v-if="scope.row.personalSignature" :src="scope.row.personalSignature"
              style="width: 50px;height:50px;border-radius: 50%;">
            <img v-else src="@/assets/noBody.png" style="width: 50px;height:50px;border-radius: 50%;">
          </template>
        </el-table-column>
        <el-table-column align="left" label="姓名" prop="name"></el-table-column>
        <el-table-column align="left" label="账号" prop="username"></el-table-column>
        <el-table-column align="left" label="单位" prop="unitName"></el-table-column>
        <el-table-column align="left" label="角色" prop="roleName"></el-table-column>
        <el-table-column align="left" label="类型">
          <template #default="scope">
            <span>{{ scope.row.front == 1 ? '客户端' : '管理端' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div> -->
    </el-drawer>
  </div>
</template>
<script setup>
import {
  workflowAdd,
  workflowEdit,
  workflowAll,
  workflowInfo,
  workflowDelete
} from '@/api/xitongpeizhi'

import {
  getUserList,
} from '@/api/user'
import {
  getAuthorityList
} from '@/api/authority'
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { Edit, CirclePlus, Upload, CircleCheck } from '@element-plus/icons-vue'
import { formToJSON } from 'axios'

// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})
const rules = reactive({
  node: [{ required: true, message: '请输入节点名', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入顺序', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  names: [{ required: true, message: '请选择用户', trigger: 'change' }],
  roles: [{ required: true, message: '请选择角色', trigger: 'change' }]
})
const zjList = ref(['本级区域', '市级区域', '区级区域'])

const appStore = useAppStore()
const activeName = ref('1')
const searchInfo = ref({
  name: '',
  type: ''
})
const typeList = ref([
  {
    name: '大中修',
    id: 1
  },
  {
    name: '配置后维修',
    id: 2
  },
  {
    name: '改变房屋布局用途维修',
    id: 3
  }
])
const form = ref({
  names: '',
  roles: [],
  name: '',
  type: 1,
  condition: 1
})
const forms = ref({
  name: '',
  type: '',
  nodes: [{
    names: [],
    condition: 1,
    elements: [],
    node: '',
    sort: '',
    type: 1
  }]
})
function search() {
  getUserList({ name: form.value.name }).then(res => {
    userData.value = res.result.data
  })
}
function reset() {
  getUserList().then(res => {
    userData.value = res.result.data
  })
}
const userStore = useUserStore()
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

const yyglForm = ref(null)

const checkedColumns = ref(['序号', '办公楼名称', '详细地址', '总建筑面积', '总层数', '出租单位', '出租面积'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).czcj) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).czcj
}
const columns = ref(['序号', '办公楼名称', '详细地址', '总建筑面积', '总层数', '出租单位', '出租面积'])
const handleColumnsChange = (val) => {
  let obj = {

  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.czcj = val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const active = ref(0)

const gzlData = ref([])
// 查询
const getTableData = async () => {
  workflowAll().then(res => {
    gzlData.value = res.result
  })
}
getTableData()
const userData = ref([])
const roleData = ref([])
onMounted(() => {
  getUserList().then(res => {
    userData.value = res.result.data
  })
  getAuthorityList().then(res => {
    roleData.value = res.result
  })
})
const dialog1 = ref(false)
const isEdit = ref(false)
function addUnit() {
  isEdit.value = false
  dialog1.value = true
}
function editData(row) {
  isEdit.value = true
  forms.value = JSON.parse(JSON.stringify(row))
  forms.value.workflowId = row.id
  workflowInfo(row.id).then(res => {
    forms.value.nodes = res.result
    forms.value.nodes.forEach(item => {
      item.names = item.elementAlias.split(',')
      item.elements = item.elements.split(',')
    })
    dialog1.value = true
  })
}
function handleClose1() {
  initForm()
  dialog1.value = false
}
function closeDialog1() {
  initForm()
  dialog1.value = false
}
const initForm = () => {
  forms.value = {
    name: '',
    type: '',
    nodes: [{
      names: [],
      condition: 1,
      elements: [],
      node: '',
      sort: '',
      type: 1
    }]
  }
}
const dialog2 = ref(false)
const table = ref(null)
function handleClose2() {
  //table.value.clearSelection()
  dialog2.value = false
}
function closeDialog2() {
  //table.value.clearSelection()
  dialog2.value = false
}
const selectedRows = ref([])
function confirm2() {
  forms.value.nodes[currentIndex.value].names = selectedRows.value.map(item => item.name)
  forms.value.nodes[currentIndex.value].elements = selectedRows.value.map(item => item.id).join(',')
  //yyglForm.value.validateField('name')
  dialog2.value = false
}
const gzlForm = ref(null)

function confirm1() {
  //forms.value.nodes[0].elements = forms.value.nodes[0].elements.join(',')
  gzlForm.value.validate(async (valid) => {
    if (valid) {
      if (!forms.value.nodes[0].node) {
        ElMessage({
          type: 'info',
          message: '请填写节点信息'
        })
        return
      }
      let res
      if (isEdit.value) {
        forms.value.nodes.forEach(item => {
          if (Array.isArray(item.elements)) {
            item.elements = item.elements.join(',')
          }
        })
        res = await workflowEdit(forms.value)
      } else {
        res = await workflowAdd(forms.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      // initForm()
      dialog1.value = false
    }
  })
}
const props1 = {
  checkStrictly: true,
  label: 'name',
  value: 'name'
}
function handleChange(val) {
  forms.value.nodes[0].elements = []
  val.forEach(item => {
    forms.value.nodes[0].elements.push(item.split(',')[0])
  })
}
const handleClose = () => {
  form.value.names = ''
  form.value.zj = ''
  form.value.type = 1
  dialogFormVisible.value = false
}
const currentIndex = ref(0)
function openDialog(index) {
  currentIndex.value = index
  forms.value.nodes.forEach(item => {
    if (Array.isArray(item.elements)) {
      item.elements = item.elements.map(n => Number(n))
    }
  })
  dialogFormVisible.value = true
}
function closeDialog() {
  dialogFormVisible.value = false
}

function confirm() {
  //forms.value.nodes[currentIndex.value].names = []
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      //forms.value.nodes[currentIndex.value].names = form.value.names.split(',')
      if (forms.value.nodes[currentIndex.value].type == 1) {
        forms.value.nodes[currentIndex.value].names = []
        roleData.value.forEach(item1 => {
          forms.value.nodes[currentIndex.value].elements.forEach(item2 => {
            if (item1.id == item2) {
              forms.value.nodes[currentIndex.value].names.push(item1.name)
            }
          })
        })
        forms.value.nodes[currentIndex.value].elements = forms.value.nodes[currentIndex.value].elements.join(',')
        //forms.value.nodes[currentIndex.value].names = forms.value.nodes[currentIndex.value].elements
      }
      // form.value.names = ''
      // form.value.zj = ''
      // form.value.type = 1
      dialogFormVisible.value = false
    }
  })
}

function addProcess() {
  if (active.value++ > 2) active.value = 0
  if (!forms.value.nodes[currentIndex.value].node) {
    ElMessage({
      type: 'info',
      message: '请填写节点信息'
    })
    return
  }
  forms.value.nodes.push(
    {
      condition: 1,
      elements: [],
      node: '',
      sort: '',
      type: 1,
      names: []
    }
  )
  //currentIndex.value++
}
function delProcess(index) {
  forms.value.nodes.splice(index, 1)
}
function openUser() {
  dialog2.value = true
  table.value?.clearSelection()
}

function handleSelectionChange(val) {
  selectedRows.value = val
}

const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await workflowDelete(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
</script>

<style lang="scss">
.gva-btn-list {
  display: flex;
  justify-content: space-between;
}

.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.renyuan-drawer {
  .top {
    display: flex;
    align-items: center;
    margin-bottom: 20px;


    .el-form-item {
      margin-bottom: 0;
      margin-left: 10px;
    }
  }

  .section-title {
    font-weight: bold;
    font-size: 20px;
    line-height: 33px;
    padding: 4px 0 4px 14px;
    color: #4E7DFD;
    position: relative;

    .tips {
      margin: 0 50px 0 10px;
      font-weight: normal;
      font-size: 16px;
      color: #606266;

      span {
        color: #4E7DFD;
      }
    }
  }

  .section-title:before {
    content: '';
    position: absolute;
    top: 12px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
  }

  .title {
    font-weight: bold;
    font-size: 20px;
    text-align: center;
  }
}

.green {
  color: #67c23a;
}

.gray {
  color: #000;
}
</style>
